import {ENV_URL} from "../config/URL";
import {getCode, wx_login} from "../api/login";
import {getGamerByUserId} from "../api/gamer";
import {getShop} from "../api/business";

function request(option) {

    const {url, data, method, header} = option

    return new Promise(((resolve, reject) => {
        uni.request({

            url:ENV_URL+url,

            data,

            method,

            header:{
                ...header,
                token:uni.getStorageSync('token')
            },

            success:async (res) => {
                if (res.data.msg === '未登录'){
                    const {code} = await getCode()
                    const loginMsg = await wx_login(code)
                    if (loginMsg.data.msg != '用户不存在') {
                        uni.setStorageSync('token', loginMsg.data.data.token);
                        uni.setStorageSync('userInfo', loginMsg.data.data.user);
                        uni.setStorageSync('couponNum', loginMsg.data.data.couponNum);
                        //判断用户是不是互娱师
                        const gamer = await getGamerByUserId({
                            id: uni.getStorageSync('userInfo').id
                        })

                        if (gamer.data.code != 500) {
                            uni.setStorageSync('gamerInfo', gamer.data.data);
                        } else {
                            uni.removeStorageSync('gamerInfo');
                        }
                        const shop = await getShop({
                            f_user_id: uni.getStorageSync('userInfo').id
                        })

                        if (shop.data.code != 500) {
                            uni.setStorageSync('shopInfo', shop.data.data);
                        } else {
                            uni.removeStorageSync('shopInfo');
                        }
                    } else {
                        uni.removeStorageSync('token');
                        uni.removeStorageSync('userInfo');
                        uni.navigateTo({url: '/subPages/subRegister/index'})
                    }
                }else{
                    resolve(res)
                }
            },
            fail: (err) => {
                reject(err)
            }
        });
    }))
}

export {
    request
}
